package com.aat.dxfy.shiro;

import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//AuthorizingRealm
public class MyRealm3 extends AuthorizingRealm {
	private static Logger log = LoggerFactory.getLogger(MyRealm3.class);

	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		// getAvailablePrincipal(principals)
		String username = (String) principals.getPrimaryPrincipal();

		Set<String> roleNames = new HashSet<String>();
		Set<String> permissions = new TreeSet<String>();
		if ("admin".equals(username)) {
			roleNames.add("system");
			permissions.add("*");
		} else if ("user".equals(username)) {
			roleNames.add("user");
			permissions.add("jsp:view:one");
		}
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		authorizationInfo.setRoles(roleNames);
		authorizationInfo.setStringPermissions(permissions);
		return authorizationInfo;
	}

	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken upToken = (UsernamePasswordToken) token;
		String username = upToken.getUsername();
		String passwd = new String(upToken.getPassword());
		if (("admin".equals(username) || "user".equals(username))
				&& "qq".equals(passwd)) {
			SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
					username, passwd, getName());
			log.info(getName() + ":QQ的账户登录");
			return authenticationInfo;
		}
		return null;
	}

}
